const express = require('express')
const router = express.Router()
const ExpressPickup = require('../db/express-pickup')
const { v4: uuidv4 } = require('uuid')

// 创建快递代取订单
router.post('/create', async (req, res) => {
  try {
    const {
      deliveryAddress,
      deliveryTime,
      itemSize,
      pickupCode,
      pickupLocation,
      baseFee,
      deliveryFee,
      tipAmount,
      selectedCoupon,
      riderGender,
      moreRequirements,
      userId,
      userName,
      userPhone
    } = req.body

    // 验证必填字段
    if (!deliveryAddress || !pickupCode || !pickupLocation) {
      return res.json({
        success: false,
        message: '配送地址、取件码、取件地点为必填项'
      })
    }

    // 生成订单ID和订单号
    const orderId = uuidv4()
    const orderNo = ExpressPickup.generateOrderNo()
    
    // 计算总金额
    const totalAmount = (baseFee || 0) + (deliveryFee || 0) + (tipAmount || 0)

    // 创建订单
    const order = new ExpressPickup({
      orderId,
      orderNo,
      deliveryAddress,
      deliveryTime,
      itemSize,
      pickupCode,
      pickupLocation,
      baseFee: baseFee || 0,
      deliveryFee: deliveryFee || 0,
      tipAmount: tipAmount || 0,
      totalAmount,
      selectedCoupon: selectedCoupon || '',
      riderGender: riderGender || '不限性别',
      moreRequirements: moreRequirements || false,
      userId: userId || 'anonymous',
      userName: userName || '匿名用户',
      userPhone: userPhone || ''
    })

    // 保存订单
    await order.save()

    // 返回成功响应
    res.json({
      success: true,
      data: {
        orderId: order.orderId,
        orderNo: order.orderNo,
        status: order.status,
        createTime: order.createTime,
        totalAmount: order.totalAmount
      },
      message: '订单创建成功'
    })

  } catch (error) {
    console.error('创建快递代取订单失败:', error)
    res.json({
      success: false,
      message: '创建订单失败，请重试'
    })
  }
})

// 获取用户订单列表
router.get('/user/:userId', async (req, res) => {
  try {
    const { userId } = req.params
    const { status, page = 1, limit = 10 } = req.query

    // 构建查询条件
    const query = { userId }
    if (status && status !== 'all') {
      query.status = status
    }

    // 分页查询
    const skip = (page - 1) * limit
    const orders = await ExpressPickup.find(query)
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(limit))

    // 获取总数
    const total = await ExpressPickup.countDocuments(query)

    res.json({
      success: true,
      data: {
        orders,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total / limit)
      },
      message: '获取订单列表成功'
    })

  } catch (error) {
    console.error('获取用户订单列表失败:', error)
    res.json({
      success: false,
      message: '获取订单列表失败'
    })
  }
})

// 获取订单详情
router.get('/detail/:orderId', async (req, res) => {
  try {
    const { orderId } = req.params
    const order = await ExpressPickup.findOne({ orderId })

    if (!order) {
      return res.json({
        success: false,
        message: '订单不存在'
      })
    }

    res.json({
      success: true,
      data: order,
      message: '获取订单详情成功'
    })

  } catch (error) {
    console.error('获取订单详情失败:', error)
    res.json({
      success: false,
      message: '获取订单详情失败'
    })
  }
})

// 更新订单状态
router.put('/status/:orderId', async (req, res) => {
  try {
    const { orderId } = req.params
    const { status, riderId, riderName, riderPhone } = req.body

    const updateData = { status, updateTime: new Date() }
    
    // 如果分配了骑手，更新骑手信息
    if (riderId) {
      updateData.riderId = riderId
      updateData.riderName = riderName
      updateData.riderPhone = riderPhone
    }

    const order = await ExpressPickup.findOneAndUpdate(
      { orderId },
      updateData,
      { new: true }
    )

    if (!order) {
      return res.json({
        success: false,
        message: '订单不存在'
      })
    }

    res.json({
      success: true,
      data: order,
      message: '订单状态更新成功'
    })

  } catch (error) {
    console.error('更新订单状态失败:', error)
    res.json({
      success: false,
      message: '更新订单状态失败'
    })
  }
})

// 取消订单
router.put('/cancel/:orderId', async (req, res) => {
  try {
    const { orderId } = req.params
    const { remarks } = req.body

    const order = await ExpressPickup.findOneAndUpdate(
      { orderId },
      { 
        status: 'cancelled',
        remarks: remarks || '用户取消订单',
        updateTime: new Date()
      },
      { new: true }
    )

    if (!order) {
      return res.json({
        success: false,
        message: '订单不存在'
      })
    }

    res.json({
      success: true,
      data: order,
      message: '订单取消成功'
    })

  } catch (error) {
    console.error('取消订单失败:', error)
    res.json({
      success: false,
      message: '取消订单失败'
    })
  }
})

// 获取所有订单（管理员用）
router.get('/all', async (req, res) => {
  try {
    const { status, page = 1, limit = 20 } = req.query

    // 构建查询条件
    const query = {}
    if (status && status !== 'all') {
      query.status = status
    }

    // 分页查询
    const skip = (page - 1) * limit
    const orders = await ExpressPickup.find(query)
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(limit))

    // 获取总数
    const total = await ExpressPickup.countDocuments(query)

    res.json({
      success: true,
      data: {
        orders,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total / limit)
      },
      message: '获取订单列表成功'
    })

  } catch (error) {
    console.error('获取所有订单失败:', error)
    res.json({
      success: false,
      message: '获取订单列表失败'
    })
  }
})

module.exports = router

